<template>
  <BaseModal
    :visible="visible"
    :title="title"
    @update:visible="emit('update:visible', $event)"
    @confirm="handleConfirm"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="resource-form"
    >
      <el-form-item label="资源名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入资源名称" />
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
          <el-option label="科技" value="科技" />
          <el-option label="金融" value="金融" />
          <el-option label="电商" value="电商" />
          <el-option label="数据" value="数据" />
          <el-option label="游戏" value="游戏" />
          <el-option label="教育" value="教育" />
          <el-option label="医疗" value="医疗" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
          <el-option label="已完成" value="已完成" />
          <el-option label="运行中" value="运行中" />
          <el-option label="维护中" value="维护中" />
        </el-select>
      </el-form-item>

      <el-form-item label="占用空间" prop="space">
        <el-input v-model="form.space" placeholder="请输入占用空间" />
      </el-form-item>
    </el-form>
  </BaseModal>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import BaseModal from '@/components/Modal/BaseModal.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  resourceData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'confirm'])

const formRef = ref(null)

const isEdit = computed(() => !!props.resourceData.id)

const title = computed(() => isEdit.value ? '编辑资源' : '新增资源')

const form = ref({
  name: '',
  type: '',
  status: '',
  space: ''
})

const rules = {
  name: [
    { required: true, message: '请输入资源名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  space: [
    { required: true, message: '请输入占用空间', trigger: 'blur' }
  ]
}

// 监听resourceData变化，用于编辑时填充表单
watch(
  () => props.resourceData,
  (newVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      form.value = { ...newVal }
    } else {
      // 重置表单
      form.value = {
        name: '',
        type: '',
        status: '',
        space: ''
      }
    }
  },
  { immediate: true }
)

const handleConfirm = async () => {
  try {
    await formRef.value.validate()
    emit('confirm', { ...form.value })
  } catch {
    ElMessage.error('请填写正确的表单信息')
  }
}
</script>

<style scoped lang="scss">
.resource-form {
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}
</style>
